// /**
//  * 讨论组件，包含多个评论和回复框
/**
 * @param {useInLog} 表示是否在讨论面板中使用 在面板中，不支持删除和编辑草稿。
 * @param {isYundouComment} 表示是否是云豆的评论，云豆评论（点击回复，不是新建评论，而是回复，按照issue当做第一条评论处理）
 */
//  */

import React from 'react';
import { Input, Checkbox } from '@teamix/ui';
import MdEditor from 'components/mdEditor';
import InlineComment from '../commentMedia/inlineComment.jsx';
import PanelComment from '../commentMedia/panelComment.jsx';
import TextAvatar from '@txdfe/at-text-avatar';
import './conversation.scss';
import { ENUM } from 'utils/constants';
import LineInfo from '../commentMedia/lineInfo';
import track from 'utils/track';
import utils from 'utils';
import intl from '../../../../../../../../../../../locale';
import sha1 from 'sha1';

const { ctrlTxt } = ENUM.getOSKeyMap();

const { pathResource, user: self } = window.FORCE;

export default class Conversation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isEditorShow: false,
      size: 'medium',
      replyComment: null,
    };
  }

  onSubmit = (value, is_draft) => {
    const {
      conversation,
      line,
      onCancel,
      side,
      from_commit,
      to_commit,
      diff,
      issueId,
      codeReviewDetail,
      useInLog,
    } = this.props;
    if (is_draft) {
      track({
        action: 'save_draft',
        page: 'Repo-MR-changes',
        mr_id: codeReviewDetail.id,
      });
    } else {
      track({
        action: useInLog ? 'view_comments_panel_post' : 'post_comment',
        page: 'Repo-MR-changes',
        mr_id: codeReviewDetail.id,
      });
    }
    let curPath = '';
    // 行内评论有diff，面板中评论没有
    if (diff) {
      curPath = diff.deleted_file ? diff.old_path : diff.new_path;
    } else {
      curPath = conversation[0].path || conversation[0].new_path;
    }
    this.props.postInlineComments({
      note: value,
      parent_note_id: conversation[0] ? conversation[0].id : '',
      line: line || conversation[0].line,
      commit_id: to_commit || from_commit || '',
      comparison_commit_id: from_commit || to_commit || '',
      is_draft,
      path: curPath,
      side: side === 'left' ? 'left' : 'right',
      issue_id: issueId || '',
    });

    if (onCancel) {
      onCancel();
    } else {
      this.hideEditor();
    }
  };

  showEditor = (comment) => {
    this.setState({
      isEditorShow: true,
      size: 'small',
      // 回复的comment,@人名，以及parent_note_id
      replyComment: comment,
    });
  };

  hideEditor = () => {
    const { useInLog, codeReviewDetail } = this.props;
    this.setState({
      isEditorShow: false,
    });

    if (useInLog) {
      track({
        action: 'view_comments_panel_cancel',
        page: 'Repo-MR-changes',
        mr_id: codeReviewDetail.id,
      });
    }
  };

  // 渲染在面板中的评论
  renderCommentInPanel = (data, hasDraft) => {
    // hasDraft 则hover不显示回复
    const { notMatched } = this.props;
    // const comment = data[0];
    return (
      <div className="panel-comment-list">
        {this.getTitle(data[0])}

        {data.map((item, index) => {
          return (
            <PanelComment
              comment={item}
              {...this.props}
              replyFn={this.showEditor}
              notMatched={notMatched}
              hasDraft={hasDraft}
              curIndex={index}
            />
          );
        })}
      </div>
    );
  };

  // 行内和面板内标题显示不一样
  getTitle = (comment) => {
    if (!comment) {
      return null;
    }
    // TODO 云豆场景需要注意，不需要解决
    const { outdated } = comment;
    const style = comment.path
      ? {}
      : {
          top: '-6px',
          background: 'transparent',
          float: 'right',
        };

    return (
      <div style={style} className={`comment-new-media-line ${outdated ? 'outdated' : ''}`}>
        {comment.path ? (
          <div className="comment-new-media-line-left">
            <LineInfo
              comment={comment}
              updateData={this.props.updateData}
              maxWidth={outdated ? '100px' : '72px'}
            />
          </div>
        ) : null}
        <div
          className="comment-new-media-line-right"
          style={comment.path ? { position: 'relative', top: '-2px' } : { width: 'auto' }}
        >
          <Checkbox
            checked={!!comment.closed}
            onChange={() => {
              this.props.toggleComment({ noteId: comment.id, closed: !comment.closed });
            }}
          >
            {comment.closed
              ? intl.get({
                  id: 'code-assets.components.diff.conversation.Resolved',
                  defaultMessage: '已解决',
                })
              : intl.get({
                  id: 'code-assets.components.diff.conversation.ToBeResolved',
                  defaultMessage: '待解决',
                })}
          </Checkbox>
          {comment.path && outdated && (
            <div className="outdated-text">
              {intl.get({
                id: 'code-assets.components.diff.conversation.Expired',
                defaultMessage: '已过期',
              })}
            </div>
          )}
        </div>
      </div>
    );
  };

  renderTimeline = (data, hasDraft) => {
    // hasDraft 则hover不显示回复
    const { notMatched, useInLog } = this.props;
    if (!data.length) {
      return null;
    }

    if (useInLog) {
      return this.renderCommentInPanel(data, hasDraft);
    }

    return (
      <div className={`timeline-wrapper ${useInLog ? 'use-in-log' : ''}`}>
        {data.map((item, index) => {
          return (
            <div className="timeline-comment-item">
              <div className="timeline-comment-item-left">
                <div className="timeline-comment-item-left-line" />
                <TextAvatar
                  text={(item.author && item.author.name) || ''}
                  image={(item.author && item.author.avatar_url) || ''}
                  radius="50%"
                  size="small"
                />
              </div>
              <div className="timeline-comment-item-right">
                {useInLog ? (
                  <PanelComment
                    comment={item}
                    {...this.props}
                    replyFn={this.showEditor}
                    notMatched={notMatched}
                    hasDraft={hasDraft}
                    curIndex={index}
                  />
                ) : (
                  <InlineComment
                    comment={item}
                    {...this.props}
                    replyFn={this.showEditor}
                    notMatched={notMatched}
                    hasDraft={hasDraft}
                  />
                )}
              </div>
            </div>
          );
        })}
      </div>
    );
  };

  renderUserAvatar = () => {
    return (
      <div className="user">
        <TextAvatar
          text={self.nickname || self.realName || ''}
          image={self.avatar || ''}
          radius="50%"
          size="small"
        />
      </div>
    );
  };

  // noDraft 是否有保存草稿按钮
  renderMd = (noDraft = false) => {
    const { onCancel } = this.props;
    const { replyComment } = this.state;
    /* 整体回复是否需要以及新建行内评论时 */
    return (
      <MdEditor
        onSubmit={noDraft ? null : this.onSubmit}
        onSubmitImmediate={this.onSubmit}
        onCancel={onCancel || this.hideEditor}
        placeholder={intl.get({
          id: 'code-assets.components.diff.conversation.EnterAComment',
          defaultMessage: '请输入评论',
        })}
        help={
          noDraft
            ? intl.get(
                {
                  id: 'code-assets.components.diff.conversation.CtrltxtShiftEnterPublishDirectly',
                  defaultMessage: '{ctrlTxt} + Shift + Enter 直接发布',
                },
                { ctrlTxt },
              )
            : intl.get(
                {
                  id: 'code-assets.components.diff.conversation.CtrltxtEnterSaveDraftCtrltxt',
                  defaultMessage: '{ctrlTxt} + Enter 存草稿，{ctrlTxt} + Shift + Enter 直接发布',
                },
                { ctrlTxt },
              )
        }
        // size={useInLog || this.state.size === 'small' ? 'small' : 'medium'}
        submitBtnText={
          noDraft
            ? ''
            : intl.get({
                id: 'code-assets.components.diff.conversation.SaveAsDraft',
                defaultMessage: '保存为草稿',
              })
        }
        initValue={replyComment && replyComment.author ? `@${replyComment.author.name} ` : ''}
        ref={(ref) => {
          this.mdRef = ref;
        }}
      />
    );
  };

  // 面板中回复只有直接发布
  renderMdInPanel = () => {
    const { onCancel, useInLog } = this.props;
    const { replyComment } = this.state;
    /* 整体回复是否需要以及新建行内评论时 */
    return (
      <MdEditor
        // onSubmit={this.onSubmit}
        onSubmitImmediate={this.onSubmit}
        onCancel={onCancel || this.hideEditor}
        placeholder={intl.get({
          id: 'code-assets.components.diff.conversation.EnterAComment',
          defaultMessage: '请输入评论',
        })}
        help={intl.get(
          {
            id: 'code-assets.components.diff.conversation.CtrltxtEnterSaveDraftCtrltxt',
            defaultMessage: '{ctrlTxt} + Enter 存草稿，{ctrlTxt} + Shift + Enter 直接发布',
          },
          { ctrlTxt },
        )}
        size={useInLog || this.state.size === 'small' ? 'small' : 'medium'} // submitBtnText={'保存为草稿'}
        initValue={replyComment && replyComment.author ? `@${replyComment.author.name} ` : ''}
        ref={(ref) => {
          this.mdRef = ref;
        }}
      />
    );
  };

  // 渲染底部是输入框还是md编辑器,面板只有编辑器，行内还额外显示input框
  renderMdOrInput = () => {
    // useInLog是用于操作历史时的标识
    const { conversation, useInLog, noDraft, isYundouComment } = this.props;
    if (useInLog) {
      return this.state.isEditorShow || !conversation.length ? (
        <div className="comment-input-md">
          <div className="input-area">{this.renderMd(true)}</div>
        </div>
      ) : null;
    } else {
      return (
        <div className="comment-input-md">
          {this.renderUserAvatar()}
          <div className="input-area">
            {/* 整体回复是否需要以及新建行内评论时 */}
            {this.state.isEditorShow || (!isYundouComment && !conversation.length) ? (
              this.renderMd(noDraft)
            ) : (
              <div className="placeholder-text" style={{ display: useInLog ? 'none' : 'block' }}>
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.components.diff.conversation.EnterAComment',
                    defaultMessage: '请输入评论',
                  })}
                  onClick={() => {
                    this.showEditor({
                      id: conversation.id,
                    });
                  }}
                  style={{ width: '100%' }}
                />
              </div>
            )}
          </div>
        </div>
      );
    }
  };

  render() {
    // notMatched是未在当前上下文匹配到此讨论的标识
    const { conversation, readOnly, useInLog, notMatched, changesReducer, mrCommentConfig } =
      this.props;
    const { allComments = [] } = changesReducer;
    const hasPermission =
      pathResource.isArchive === 'false' &&
      utils.allowComments(allComments.length, mrCommentConfig);

    // 讨论中是否有草稿：如果有，则不展示回复框
    const hasDraft = conversation.some((item) => item.is_draft);

    return (
      <div className={`conversation ${useInLog ? 'use-in-log' : ''}`}>
        {conversation && conversation[0] && !readOnly ? (
          <div
            className={`conversation-anchor ${sha1(conversation[0].path || '')}_comment_jump_item`}
            id={`anchor_conversation_${conversation[0].id}`}
          />
        ) : null}
        <div>{this.renderTimeline(conversation, hasDraft)}</div>
        {/* 有草稿可以继续回复 */}
        {hasPermission && !readOnly && !notMatched ? this.renderMdOrInput() : null}
      </div>
    );
  }
}
